package com.mzba.place.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.ReportListAdapter;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportInfoGson;
import com.mzba.place.ui.widget.CustomListView;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageLoader;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 
 * @author 06peng
 *
 */
public class CautionsActivity extends BasicActivity implements Callback {

	private CustomListView listView;
	private List<ReportEntity> reports;
	private ReportListAdapter reportListAdapter;
	private ImageLoader mImageLoader;
	private double localLat;
	private double localLon;
	public PlaceApplication app;
	public LocationClient mLocClient;
	private Handler handler;
	
	private final int init_reports = 1;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.fragment_report_list);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		setTitle("警示区域");
		app = (PlaceApplication) getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        app.getMyListener().setHander(handler);
        mLocClient = app.mLocationClient;
		mImageLoader = ImageLoader.getInstance(this);
		
		listView = (CustomListView) findViewById(R.id.list_report);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent intent = new Intent();
				intent.setClass(CautionsActivity.this, ReportDetailActivity.class);
				intent.putExtra("report_detail", reportListAdapter.getReportList().get(arg2-1));
				startActivity(intent);
			}
		});
		menuMyPosition();
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return false;
	}
	
	OnScrollListener onScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				mImageLoader.lock();
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				mImageLoader.unlock();
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				mImageLoader.lock();
				break;
			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			
		}
	};
	
	/**
	 * locate to my position
	 */
	public void menuMyPosition() {
		loading();
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			
		option.setCoorType("bd09ll");			
		option.setAddrType("all");	
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);      
		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}
	
	public void execute(int mes, Object obj) {
		try {
			String response = null;
			switch (mes) {
			case init_reports:
				String url = UrlConfig.cautions;
				url += "?auth_token=" + AppContext.getInstance().getAuthToken();
				response = HttpUtils.doGet(url);
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					ReportInfoGson reportGson = gson.fromJson(response, ReportInfoGson.class);
					if (reportGson != null) {
						reports = reportGson.getReports();
					}
				}
				handler.sendEmptyMessage(init_reports);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	};

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_reports:
			if (reports != null && !reports.isEmpty()) {
				reportListAdapter = new ReportListAdapter(this, reports, localLat, localLon, mImageLoader);
				listView.setAdapter(reportListAdapter);
			} else {
				List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("value", "暂无数据");
				SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.empty_listitem, 
						new String[] {"value"}, new int[] {R.id.value});
				listView.setAdapter(adapter);
			}
			break;
		case AppContext.LOCATE:
			destroyDialog();
			localLat = app.latitude;
			localLon = app.longitude;
			UICore.eventTask(this, this, init_reports, null, true);
			break;
		default:
			break;
		}
		return false;
	}
	
}
